﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

using boda.net.wpf.application.login.Views;
using boda.net.wpf.core.Dialogs;
using boda.net.wpf.core.Ioc;
using boda.net.wpf.share.Events;
using boda.net.wpf.share.Models;

using Prism.Commands;

using ReactiveUI;
using ReactiveUI.Fody.Helpers;

namespace boda.net.wpf.application.login.ViewModels;
public class LoginViewModel : ReactiveObject
{
    [Reactive]
    public CurrentUser CurrentUser { get; set; } = new CurrentUser();


    public DelegateCommand<LoginView> LoadaCommand => new DelegateCommand<LoginView>(async (v) =>
    {
        _image = v.Image as Image;


        await refreshCaptcha();
    });


    public DelegateCommand RefreshImageCommand => new DelegateCommand(async () =>
    {
        await refreshCaptcha();
    });

    private async Task refreshCaptcha()
    {
        using (HttpClient client = new HttpClient())
        {
            // 设置Authorization头
            //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            //// 构造请求内容（可选）
            //string requestBody = "your_request_body";
            //HttpContent content = new StringContent(requestBody);

            // 发送POST请求
            try
            {
                HttpResponseMessage response = await client.GetAsync("http://localhost:5005/api/sysAuth/captcha");

                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    JsonSerializerOptions options = new JsonSerializerOptions
                    {
                        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                        IgnoreReadOnlyProperties = true,
                        PropertyNameCaseInsensitive = true
                    };

                    var cache = JsonSerializer.Deserialize<HttpResponse<CaptchaModel>>(responseContent, options);
                    var base64Image = cache?.Result?.Img;
                    CurrentUser.CodeId = cache?.Result?.Id ?? "0";
                    SetImageSource(base64Image);
                    Console.WriteLine("请求成功：" + responseContent);
                }
                else
                {
                    Console.WriteLine("请求失败，HTTP状态码：" + response.StatusCode);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取验证码错误: " + ex.Message);
            }
        }
    }

    public DelegateCommand LoginCommand => new DelegateCommand(async () =>
    {
        if (string.IsNullOrEmpty(CurrentUser.Account) || string.IsNullOrEmpty(CurrentUser.Password))
        {
            PopupBox.Show("用户名或者密码为空!");
            return;
        }

        try
        {
            using (HttpClient client = new HttpClient())
            {
                var jsonRequest = JsonSerializer.Serialize<CurrentUser>(CurrentUser);
                StringContent content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
                // 发送POST请求
                HttpResponseMessage response = await client.PostAsync("http://localhost:5005/api/sysAuth/login", content);

                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    JsonSerializerOptions options = new JsonSerializerOptions
                    {
                        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                        IgnoreReadOnlyProperties = true,
                        PropertyNameCaseInsensitive = true
                    };

                    var loginRes = JsonSerializer.Deserialize<HttpResponse<LoginResponse>>(responseContent, options);

                    HttpResponseMessage response1 = await client.GetAsync("http://localhost:5005/api/sysDictData/list?DictTypeId=1");
                    // 处理响应
                    if (response1.IsSuccessStatusCode)
                    {
                        string responseContent1 = await response1.Content.ReadAsStringAsync();

                    }
                    else
                    {
                        Console.WriteLine("请求失败，HTTP状态码：" + response.StatusCode);
                    }
                }
                else
                {
                    Console.WriteLine("请求失败，HTTP状态码：" + response.StatusCode);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("用户登录出错: " + ex.Message);
        }

        PopupBox.Show("登录成功!");
        // 用户登录成功后，给出通知
        PrismProvider.EventAggregator.GetEvent<LoginSuccessEvent>().Publish(CurrentUser);
    });

    private Image _image = new();
    // 设置Image的Source属性为Base64编码的图像
    private void SetImageSource([NotNull] string? base64Image)
    {
        // 获取图像的字节流
        byte[] imageBytes = Convert.FromBase64String(base64Image);

        // 创建一个内存流
        MemoryStream ms = new MemoryStream(imageBytes);

        // 创建位图对象
        BitmapImage bitmap = new BitmapImage();

        // 设置缓存大小和读取方式
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.CreateOptions = BitmapCreateOptions.IgnoreImageCache;

        // 加载位图
        bitmap.BeginInit();
        bitmap.StreamSource = ms;
        bitmap.EndInit();

        // 设置Image控件的源
        _image.Source = bitmap;
    }
}
